package com.ihep;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @className: RSAEncrypt
 * @description: RSA加密解密类
 * @date: 2020/11/12
 * @author: cakin
 */
public class RSAEncrypt {
    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 功能描述：随机生成密钥对,并保存到文件
     *
     * @param filePath 密钥对存放路径
     * @author cakin
     * @date 2020/11/12
     */
    public static void genKeyPair(String filePath) {
        // 密钥对生成器
        KeyPairGenerator keyPairGen = null;
        try {
            // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        try {
            // 得到公钥字符串
            String publicKeyString = Base64.encode(publicKey.getEncoded());
            // 得到私钥字符串
            String privateKeyString = Base64.encode(privateKey.getEncoded());
            // 将密钥对写入到文件
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从公钥文件中得到公钥字符串
     *
     * @param path 公钥输入流
     * @return String 公钥字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public static String loadPublicKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/publicKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            /** sb的值如下，该字符串是从公钥文件中获取的，它称之为公钥字符串
             * MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgbgCkfwSK/eC0QGoxN01P1CZI1mCTwRp5qITKrbJWhw2S2LMdR3iZCALy9QuHiWf5O
             * 1axGGpoZF8Ljrk83oXRQmBpVyCe2JcfVHs4igfINb2kdZ+B0Awd/O8fVEMkeuaEtFEULsZSF8hBrKYG1KrzB/lz4hPa11fSpooANMUaIw
             * IDAQAB
             */
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }

    /**
     * 从公钥字符串中得到RSA公钥
     *
     * @param publicKeyStr 公钥字符串
     * @return RSAPublicKey RSA公钥
     * @throws Exception 加载公钥时产生的异常
     */
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从私钥文件中得到私钥字符串
     *
     * @param path 私钥文件名所在路径
     * @return String
     * @throws Exception
     */
    public static String loadPrivateKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/privateKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            /** 该字符串从私钥文件中获取，称之为私钥字符串
             * MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALaIDyyav7J8oD/8sONfP772aa1foDlHmoXRArqe+2po14c1q7nGR8DLk
             * 55J0sgxt/EOvtvxtwo4cPFtoLSBzdKVn/ZmR7uyHQXsMzqcmz7n7DGAzNNqxlu0SLHVjZ4HscWxnC+dGa037Ec9m5DKRT6aMckNmxZp3G
             * xic9wzId6zAgMBAAECgYEAhpOUFH/XvEH0aJjm1gzA1AubaI8rc2/edrDeQTe8B/1agr7IaMTO3E97++VT+fPmOV10zHbPTELGysnYBZ3
             * 6X/wLaKs+GMO/uewNAsyu46u3izwNVCygBiM62mlmhk3Y9J8ZcmoQHzXGV0p0TuGJsIlAofCAN1ielWLPcEVUPckCQQDoQm4GKe2C26oU
             * aXRwLy2WLczfmqLTlJ8QyJs8ruL78JikhDgLWaLPBJ+lHmTxahC4HjJ9LhNxNVcpbyMiHhM1AkEAyTBjkOGwBJTlYMmS1hn6BoqA5xCRF
             * Iv8gZZMxj+xcvSSEfZU9ObVArOBQRUoIO3GdsyaVfG/DNwuP7zGI16/RwJBAMfyIEu4HpsvxeyKmE3Xn5QQ27WHpzMkWAeX22RTXl7r0k
             * yW8rR6txkm7tS0JMxbtgb7IBX564zjEaU+4u0FHR0CQG+v+zYM9Ag3GHd4r5lH5nMHJLQhkEjVxaGy7IAKD9p/Ry/NjjA+jPXo7NJSimp
             * tVYXR48PeZm8fNFWR2HT+PjUCQFu3yN71iiXA0EW35Y1HHIE814gUV/O5T4gpUNzK9NLvHLFQNbzgoZER5yIGgBWDju1keBkojm8P69A7
             * qdtXILU=
             */
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }

    /**
     * 从私钥字符串中得到RSA私钥
     *
     * @param privateKeyStr 私钥字符串
     * @return RSAPrivateKey RSA私钥
     * @throws Exception 加载私钥时产生的异常
     */
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 公钥加密过程
     *
     * @param publicKey     RSA公钥
     * @param plainTextData 明文数据，以字节数组存储
     * @return byte[] 加密后的字节数组
     * @throws Exception 加密过程中的异常信息
     */
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            // 初始化算法:公钥加密
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 公钥加密后的字节数组
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥加密过程
     *
     * @param privateKey    RSA私钥
     * @param plainTextData 明文数据，以字符数组的形式存在
     * @return byte[] 加密后的密文数据，以字符数组的形式存在
     * @throws Exception 加密过程中的异常信息
     */
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // 初始化算法：私钥加密
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            // 加密后的密文数据，以字符数组的形式存在
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥解密过程
     *
     * @param privateKey 私RSA钥
     * @param cipherData 以字符数组形式存在的密文数据
     * @return byte[] 以字符数组形式存在的明文数据
     * @throws Exception 解密过程中的异常信息
     */
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            // 初始化解密算法：私钥解密
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // 解密，生成以字符数组形式存在的明文数据
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 公钥解密过程
     *
     * @param publicKey  RSA公钥
     * @param cipherData 以字符数组形式存在的密文数据
     * @return byte[]：以字符数组形式存在的明文数据
     * @throws Exception 解密过程中的异常信息
     */
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            // 初始化加密算法：公钥解密
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            // 以字符数组形式存在的明文数据
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 字节数据转十六进制字符串
     *
     * @param data 输入数据
     * @return 十六进制内容
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }
}
